package com.zj.fx.controller.month;

import com.github.pagehelper.PageInfo;
import com.zj.fx.common.base.BaseController;
import com.zj.fx.common.domain.AjaxResult;
import com.zj.fx.common.domain.ResultTable;
import com.zj.fx.model.custom.Tablepar;
import com.zj.fx.model.info.*;
import com.zj.fx.model.month.*;
import com.zj.fx.model.rpa.*;
import com.zj.fx.service.info.*;
import com.zj.fx.service.month.*;
import com.zj.fx.service.rpa.RpaTaskDtlService;
import com.zj.fx.service.rpa.RpaTransdataService;
import com.zj.fx.shiro.util.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 月度评价任务台账Controller
 *
 * @author SQL
 * @ClassName: MonthEvaluationController
 * @date 2023-06-09 14:44:21
 */
@Api(value = "月度评价任务台账")
@Controller
@RequestMapping("/MonthEvaluationController")
public class MonthEvaluationController extends BaseController {

    private String prefix = "month/monthEvaluation";

    @Autowired
    private MonthEvaluationService monthEvaluationService;

    @Autowired
    private InfoSupplyService infoSupplyService;

    @Autowired
    private MonthSupplytaskService monthSupplytaskService;

    @Autowired
    private MonthSupplytaskDtlService monthSupplytaskDtlService;

    @Autowired
    private InfoTargetService infoTargetService;

    @Autowired
    private InfoNecessaryService infoNecessaryService;

    @Autowired
    private MonthNecessaryService monthNecessaryService;

    @Autowired
    private InfoProjectService infoProjectService;

    @Autowired
    private MonthResultService monthResultService;

    @Autowired
    private InfoSubcompanyService infoSubcompanyService;

    @Autowired
    private MonthAuditSubService monthAuditSubService;

    @Autowired
    private RpaTaskDtlService rpaTaskDtlService;

    @Autowired
    private RpaTransdataService rpaTransdataService;

    /**
     * 月度评价任务台账页面展示
     *
     * @param model
     * @return String
     * @author SQL
     */
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/view")
    @RequiresPermissions("gen:monthEvaluation:view")
    public String view(ModelMap model) {
        return prefix + "/list";
    }

    /**
     * list集合
     *
     * @param tablepar
     * @param
     * @return
     */
    //@Log(title = "月度评价任务台账", action = "111")
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/list")
    @RequiresPermissions("gen:monthEvaluation:list")
    @ResponseBody
    public ResultTable list(Tablepar tablepar, MonthEvaluation monthEvaluation) {
        PageInfo<MonthEvaluation> page = monthEvaluationService.list(tablepar, monthEvaluation);
        return pageTable(page.getList(), page.getTotal());
    }

    /**
     * 新增跳转
     */
    @ApiOperation(value = "新增跳转", notes = "新增跳转")
    @GetMapping("/add")
    public String add(ModelMap modelMap) {
        return prefix + "/add";
    }

    /**
     * 生成月度评价任务
     *
     * @param
     * @return
     */
    //@Log(title = "月度评价任务台账新增", action = "111")
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping("/add")
    @RequiresPermissions("gen:monthEvaluation:add")
    @ResponseBody
    @Transactional
    public AjaxResult add(@RequestBody MonthEvaluation monthEvaluation) {
        String month = monthEvaluation.getEvaluationDate();
        //创建月评价任务完成三部分新增（1、月评价任务本表新增 2、供电所评价任务主表 3、供电所评价任务明细表）
        //1、月评价任务本表新增
        monthEvaluation.setTaskName(monthEvaluation.getEvaluationDate()+"月评价任务");
        monthEvaluation.setStatus(MonthConstant.NOT);
        monthEvaluation.setCreateTime(new Date());
        monthEvaluation.setCreateUserId(ShiroUtils.getUserId());
        monthEvaluation.setCreateUserName(ShiroUtils.getUser().getUsername());
        String evaluationId = monthEvaluationService.insertSelectiveReturnId(monthEvaluation);
        if (evaluationId != null) {
            //2、供电所评价任务主表
            //2.1 查询供电所名单
            List<InfoSupply> infoSupplies = infoSupplyService.queryList();
            for (InfoSupply infoSupply:infoSupplies) {
                MonthSupplytask monthSupplytask = new MonthSupplytask();
                monthSupplytask.setTaskMonth(month);
                monthSupplytask.setSupplyId(infoSupply.getId());
                monthSupplytask.setSupplyName(infoSupply.getName());
                monthSupplytask.setTaskState(MonthConstant.TASK_STATE_NOFILL);
                monthSupplytask.setCreateDate(new Date());
                monthSupplytask.setFkEvaluationId(evaluationId);
                monthSupplytask.setFkSubcompanyId(infoSupply.getOrganization());
                monthSupplytask.setSubcompanyName(infoSupply.getOrganizationName());
                int addTaskNum = monthSupplytaskService.insertSelective(monthSupplytask);
                if (addTaskNum>0){
                    //3、供电所评价任务明细表新增
                    //3.1查询管理提升指标并新增至供电所填报明细表
                    List<InfoTarget> infoTargets = infoTargetService.selectAll();
                    for (InfoTarget infoTarget : infoTargets) {
                        monthSupplytaskDtlService.generategrade5(infoSupply, monthSupplytask, infoTarget);
                    }
                    //3.2查询管理提升项目中的四级项目并新增至供电所填报明细表
                    List<InfoProject> infoProjects = infoProjectService.selectgrade4();
                    for (InfoProject infoProject : infoProjects) {
                        monthSupplytaskDtlService.generategrade4(infoSupply, monthSupplytask, infoProject);
                    }
                    //3.3查询必要项目并新增至供电所填报明细表
                    List<InfoNecessary> infoNecessaries = infoNecessaryService.selectAll();
                    for (InfoNecessary infoNecessary : infoNecessaries) {
                        monthNecessaryService.generateNes(infoSupply, monthSupplytask, infoNecessary);
                    }

                    /*
                    查询四级项目下五级项目有生成分数且总扣分=0的。将对应四级项目分数更新为满分
                    更新对应四级项目的得分为满分----（有个坑，四级下面多个五级项目的可能有的是默认满分有的需要手填）
                    或者考虑列表查询时候做处理
                     */
//                    List<MonthSupplytaskDtl> monthSupplytaskDtls = monthSupplytaskDtlService.findFullMark(monthSupplytask);
//                    for (MonthSupplytaskDtl monthSupplytaskDtl : monthSupplytaskDtls) {
//                        MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
//                        MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
//                        criteria.andProGradeEqualTo(MonthConstant.DTL_PROGRADE_FOUR);
//                        criteria.andNumEqualTo(monthSupplytaskDtl.getId());
//                        criteria.andFkTaskIdEqualTo(monthSupplytask.getId());
//                        List<MonthSupplytaskDtl> monthSupplytaskDtls1 = monthSupplytaskDtlService.selectByExample(monthSupplytaskDtlExample);
//                        MonthSupplytaskDtl monthSupplytaskDtl1 = monthSupplytaskDtls1.get(0);
//                        monthSupplytaskDtl1.setSelfScore(monthSupplytaskDtl1.getFullMark());
//                        monthSupplytaskDtlService.updateByPrimaryKeySelective(monthSupplytaskDtl1);
//                    }

                    List<MonthSupplytaskDtl> monthSupplytaskDtls = monthSupplytaskDtlService.findFinishMark(monthSupplytask);
                    for (MonthSupplytaskDtl monthSupplytaskDtl : monthSupplytaskDtls) {
                        MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
                        MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
                        criteria.andProGradeEqualTo(MonthConstant.DTL_PROGRADE_FOUR);
                        criteria.andNumEqualTo(monthSupplytaskDtl.getId());
                        criteria.andFkTaskIdEqualTo(monthSupplytask.getId());
                        List<MonthSupplytaskDtl> monthSupplytaskDtls1 = monthSupplytaskDtlService.selectByExample(monthSupplytaskDtlExample);
                        MonthSupplytaskDtl monthSupplytaskDtl1 = monthSupplytaskDtls1.get(0);

                        BigDecimal sumkoufen = new BigDecimal(monthSupplytaskDtl.getSumSelfScore());
                        BigDecimal fullMark = new BigDecimal(monthSupplytaskDtl1.getFullMark());

                        if (sumkoufen.compareTo(fullMark)>0){
                            monthSupplytaskDtl1.setSelfScore(BigDecimal.ZERO.setScale(2).toString());
                        } else {
                            monthSupplytaskDtl1.setSelfScore(fullMark.subtract(sumkoufen).setScale(2).toString());
                        }

                        monthSupplytaskDtlService.updateByPrimaryKeySelective(monthSupplytaskDtl1);
                    }
                    //----------------20231127新增，轮询RPA月度任务明细表，如存在有效转换数据，依次更新对应指标的值----START
                    //查询月度RPA任务明细
                    String taskmonth = monthEvaluation.getEvaluationDate().replaceAll("-","");
                    RpaTaskDtlExample rpaTaskDtlExample = new RpaTaskDtlExample();
                    rpaTaskDtlExample.createCriteria().andTaskmonthEqualTo(taskmonth);
                    List<RpaTaskDtl> rpaTaskDtls = rpaTaskDtlService.selectByExample(rpaTaskDtlExample);
                    for (RpaTaskDtl rpaTaskDtl : rpaTaskDtls) {
                        //查询对应任务明细中对应供电所的有效数据
                        RpaTransdataExample rpaTransdataExample = new RpaTransdataExample();
                        rpaTransdataExample.createCriteria().andTaskmonthEqualTo(taskmonth).andTypenumEqualTo(rpaTaskDtl.getTypenum()).andSelfsupplyidEqualTo(infoSupply.getId());
                        List<RpaTransdata> rpaTransdataList = rpaTransdataService.selectByExample(rpaTransdataExample);
                        for (RpaTransdata rpaTransdata : rpaTransdataList) {
                            String targetid = rpaTransdata.getTargetid();
                            String taskId = monthSupplytask.getId();
                            MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
                            monthSupplytaskDtlExample.createCriteria().andFkTaskIdEqualTo(taskId).andNumEqualTo(targetid);
                            List<MonthSupplytaskDtl> monthSupplytaskDtlList = monthSupplytaskDtlService.selectByExample(monthSupplytaskDtlExample);
                            if (monthSupplytaskDtlList.size()==1){
                                String id = monthSupplytaskDtlList.get(0).getId();
                                String value = rpaTransdata.getValue();
                                MonthSupplytaskDtl monthSupplytaskDtl = new MonthSupplytaskDtl();
                                monthSupplytaskDtl.setId(id);
                                monthSupplytaskDtl.setSelfValue(value);
                                monthSupplytaskDtlService.updateSelf4Rpaauto(monthSupplytaskDtl);
                                //回写更新结果
                                rpaTransdata.setIsfinish(RpaConstant.IS);
                                rpaTransdata.setTaskid(id);
                                rpaTransdataService.updateByPrimaryKeySelective(rpaTransdata);
                            }
                        }
                    }
                    //----------------20231127新增，轮询RPA月度任务明细表，如存在有效转换数据，依次更新对应指标的值----END
                }
            }
            // 新功能 增加分公司审核记录
            List<InfoSubcompany> infoSubcompanies = infoSubcompanyService.queryList();
            for (InfoSubcompany infoSubcompany : infoSubcompanies) {
                MonthAuditSub monthAuditSub = new MonthAuditSub();
                monthAuditSub.setFkTaskId(evaluationId);
                monthAuditSub.setFkSubcompanyId(infoSubcompany.getId());
                monthAuditSub.setSubcompanyName(infoSubcompany.getName());
                monthAuditSub.setTaskMonth(monthEvaluation.getEvaluationDate());
                monthAuditSub.setTaskState(MonthConstant.NOT);
                monthAuditSubService.insertSelective(monthAuditSub);
            }
            return success();
        } else {
            return error();
        }
    }

    /**
     * 月度评价任务台账删除
     *
     * @param ids
     * @return
     */
    //@Log(title = "月度评价任务台账删除", action = "111")
    @ApiOperation(value = "删除", notes = "删除")
    @DeleteMapping("/remove")
    @RequiresPermissions("gen:monthEvaluation:remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        int b = monthEvaluationService.deleteByPrimaryKey(ids);
        if (b > 0) {
            return success();
        } else {
            return error();
        }
    }


    /**
     * 修改跳转
     *
     * @param id
     * @param
     * @return
     */
    @ApiOperation(value = "修改跳转", notes = "修改跳转")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap map) {
        map.put("MonthEvaluation", monthEvaluationService.selectByPrimaryKey(id));

        return prefix + "/edit";
    }

    /**
     * 修改保存
     */
    //@Log(title = "月度评价任务台账修改", action = "111")
    @ApiOperation(value = "修改保存", notes = "修改保存")
    @RequiresPermissions("gen:monthEvaluation:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MonthEvaluation monthEvaluation) {
        return toAjax(monthEvaluationService.updateByPrimaryKeySelective(monthEvaluation));
    }

    /**
     * 检查用户
     *
     * @param
     * @return
     */
    @ApiOperation(value = "检查任务唯一", notes = "检查任务唯一")
    @PostMapping("/checkMonthUnique")
    @ResponseBody
    public int checkMonthUnique(MonthEvaluation monthEvaluation) {
        int b = monthEvaluationService.checkNameUnique(monthEvaluation);
        if (b > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 查看上报进度跳转
     *
     * @param id
     * @param
     * @return
     */
    @ApiOperation(value = "查看上报进度跳转", notes = "查看上报进度跳转")
    @GetMapping("/findFillPlan/{id}")
    public String findFillPlan(@PathVariable("id") String id, ModelMap map) {
        map.put("evaluationId", id);
//        return prefix + "/fillplan";
        return prefix + "/subcommitplan";
    }

    /**
     * 查看审核进度跳转
     *
     * @param id
     * @param
     * @return
     */
    @ApiOperation(value = "查看审核进度跳转", notes = "查看审核进度跳转")
    @GetMapping("/findAuditPlan/{id}")
    public String findAuditPlan(@PathVariable("id") String id, ModelMap map) {
        map.put("evaluationId", id);
        return prefix + "/auditplan";
    }

    /**
     * 查看实时结果跳转
     *
     * @param taskMonth
     * @param
     * @return
     */
    @ApiOperation(value = "查看审核进度跳转", notes = "查看审核进度跳转")
    @GetMapping("/findResult/{taskMonth}")
    public String findResult(@PathVariable("taskMonth") String taskMonth, ModelMap map) {
        map.put("taskMonth", taskMonth);
        return prefix + "/viewResult";
    }

    /**
     * 发布结果
     *
     * @param 
     * @param
     * @return
     */
    @ApiOperation(value = "发布结果", notes = "发布结果")
    @GetMapping("/issueResult/{id}")
    @ResponseBody
    @Transactional
    public AjaxResult issueResult(@PathVariable("id") String id) {
        //0、根据任务年月查询对应月度管理任务
        MonthEvaluation monthEvaluation = monthEvaluationService.selectByPrimaryKey(id);
        //一、发布结果状态校验
        //1、已发布的不能重复发布
        if (MonthConstant.ISSUE_FINISH.equals(monthEvaluation.getStatus())){
            return AjaxResult.error("当前评价任务对应结果已发布，不能重复发布");
        }
        //2、当前任务下的所有供电所任务均为审核完成才允许发布
        MonthSupplytaskExample monthSupplytaskExample = new MonthSupplytaskExample();
        MonthSupplytaskExample.Criteria criteria = monthSupplytaskExample.createCriteria();
        criteria.andFkEvaluationIdEqualTo(id);
        criteria.andTaskStateNotEqualTo(MonthConstant.DTL_STATE_ISFINISHED);
        List<MonthSupplytask> monthSupplytaskList = monthSupplytaskService.selectByExample(monthSupplytaskExample);
        if (monthSupplytaskList.size()>0){
            String supplyName = monthSupplytaskList.get(0).getSupplyName();
            return AjaxResult.error("当前评价任务中"+supplyName+"任务未审核完成,不允许发布");
        }
        //二、发布后状态变更
        //1、评价管理主表
        monthEvaluation.setStatus(MonthConstant.ISSUE_FINISH);
        monthEvaluation.setIssueTime(new Date());
        monthEvaluationService.updateByPrimaryKeySelective(monthEvaluation);
        //2、月度结果主表
        //查询所有对应业务下的供电所评价任务
//        MonthSupplytaskExample monthSupplytaskExample2 = new MonthSupplytaskExample();
//        MonthSupplytaskExample.Criteria criteria2 = monthSupplytaskExample2.createCriteria();
//        criteria2.andFkEvaluationIdEqualTo(id);
//        List<MonthSupplytask> monthSupplytaskList2 = monthSupplytaskService.selectByExample(monthSupplytaskExample2);
//        for (MonthSupplytask monthSupplytask : monthSupplytaskList2) {
//            MonthResultExample monthResultExample = new MonthResultExample();
//            MonthResultExample.Criteria criteria1 = monthResultExample.createCriteria();
//            criteria1.andFkTaskIdEqualTo(monthSupplytask.getId());
//            List<MonthResult> monthResults = monthResultService.selectByExample(monthResultExample);
//            for (MonthResult monthResult : monthResults) {
//                monthResult.setIsIssue(MonthConstant.ISSUE_FINISH);
//                monthResultService.updateByPrimaryKeySelective(monthResult);
//            }
//        }
        String taskmonth = monthEvaluation.getEvaluationDate();
        MonthResult monthResult = new MonthResult();
        monthResult.setTaskMonth(taskmonth);
        List<MonthResult> monthResults = monthResultService.list4Score(monthResult);
        monthResults = monthResults.stream().sorted(Comparator.comparing(MonthResult::getTotalScore).reversed()).collect(Collectors.toList());
        for (int i = 1; i <= monthResults.size(); i++) {
            MonthResult result = monthResults.get(i-1);
            result.setFinalrank(String.valueOf(i));
            result.setIsIssue(MonthConstant.ISSUE_FINISH);
            monthResultService.updateByPrimaryKeySelective(result);
        }
        return AjaxResult.success("结果发布成功");
    }

    /**
     * 查询任务对应的最新月份
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "查询任务对应的最新月份", notes = "查询任务对应的最新月份")
    @GetMapping("/getNewestMonth")
    @ResponseBody
    public AjaxResult getNewestMonth() {
        MonthEvaluation monthEvaluation = monthEvaluationService.getNewestMonth();
        return AjaxResult.successData(200,monthEvaluation);
    }

    /**
     * 查看PPA数据同步状态跳转
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "查看PPA数据同步状态跳转", notes = "查看PPA数据同步状态跳转")
    @GetMapping("/viewrpa")
    public String viewrpa() {
        return prefix + "/viewrpa";
    }


}
